<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title></title>
</head>
<body>
<div id="comments"></div>
<button id="loadMore">Load More Comments</button>
<script>
    // MutationObserver 是一个浏览器提供的 API，用于监视 DOM 树的变化。
    // 当你需要在 DOM 发生变化时执行某些操作时，MutationObserver 非常有用。它可以监视节点的添加、删除、属性变化等。
    // 对性能会产生影响，所以需要谨慎使用。
    const observer = new MutationObserver((mutationsList, observer) => {
        console.log(mutationsList);
        for (let mutation of mutationsList) {
            if (mutation.type === 'childList') {
                console.log('New comments loaded.');
                // 对新加载的评论进行处理，例如添加事件监听器
                console.log(mutation.addedNodes);
                mutation.addedNodes.forEach(node => {
                    if (node.nodeType === Node.ELEMENT_NODE) {
                        node.addEventListener('click', () => {
                            console.log('Comment clicked:', node.textContent);
                        });
                    }
                });
            }
        }
    });

    const config = { childList: true };
    const targetNode = document.getElementById('comments');
    observer.observe(targetNode, config);

    document.getElementById('loadMore').addEventListener('click', () => {
        fetchComments().then(comments => {
            comments.forEach(comment => {
                const commentElement = document.createElement('div');
                commentElement.textContent = comment.text;
                targetNode.appendChild(commentElement);
            });
        });
    });

    function fetchComments() {
        return new Promise(resolve => {
            setTimeout(() => {
                resolve([
                    { text: 'Comment 1' }
                ]);
            }, 500);
        });
    }
</script>
</body>
</html>

